######################################################################################
#
# This file was provided as part of the SharePoint Mystery Deployment package
# Created by Christopher Kimbell (http://sharepointmystery.com)
#
######################################################################################

# -----------------------------------------------------------------
# Creates an object used to manipulate a supporting service
# -----------------------------------------------------------------
function New-SupportingService()
{
    $obj=new-object PSObject -Property @{
      Name = "";
      Servers = @($env:computername);
    }
    # -----------------------------------------------------------------
    # Validates the information in the object
    # -----------------------------------------------------------------
    Add-Method $obj "Validate" `
    {
        Write-Operation "    Service"
        Validate-NotEmpty "Name" $this.Name
        Validate-NotEmpty "Server" $this.Server
    }
    # -----------------------------------------------------------------
    # Provisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Provision" `
    {
		foreach($server in $this.Servers)
		{
			Write-Operation "Starting Service $($this.Name) on $($server)"
			$services = Get-SPServiceInstance -Server $server
			
			$instance = $services | where-object {$_.TypeName -eq $this.Name}
			if($instance -ne $null)
			{
				Start-SPServiceInstance -Identity $instance
			}
			else	
			{
				Terminate("Service $($this.Name) was not found on server $($this.Server)")
			}
		}		
    }
    # -----------------------------------------------------------------
    # Unprovisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Unprovision" `
    {
		foreach($server in $this.Servers)
		{
			Write-Operation "Starting Service $($this.Name) on $($server)"
			$services = Get-SPServiceInstance -Server $server
			
			$instance = $services | where-object {$_.TypeName -eq $this.Name}
			if($instance -ne $null)
			{
				Stop-SPServiceInstance -Identity $instance -Confirm:$false
			}
			else	
			{
				Terminate("Service $($this.Name) was not found on server $($this.Server)")
			}
		}
    }
    return $obj
}
